package com.jinghua.treatment.wechat.pay;

import com.jinghua.treatment.tools.IDGenerator;
import com.jinghua.treatment.tools.PropertyUtil;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;

import javax.net.ssl.SSLContext;
import java.io.File;
import java.io.FileInputStream;
import java.net.URI;
import java.net.URL;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

public class WechatPay {

    public static void main(String args[]){

        TreeMap<String, String> xmlData = new TreeMap<String, String>();
        xmlData.put("mch_appid", PropertyUtil.getConfig("wechat.appId"));
        xmlData.put("mchid", PropertyUtil.getConfig("wcpay.mchId"));
        xmlData.put("nonce_str", IDGenerator.uuid().substring(0,16));
        xmlData.put("partner_trade_no", IDGenerator.uuid().substring(0,10));
        xmlData.put("openid", "ozT4P1UvPKUJnWua_owrINxEYaHI");
        xmlData.put("check_name", "NO_CHECK");
        xmlData.put("amount", "1");
        xmlData.put("desc", "赞赏了您");
        xmlData.put("spbill_create_ip", "101.71.37.41");
        String sign  = getSign(xmlData,PropertyUtil.getConfig("wcpay.key"));
        xmlData.put("sign", sign);

        String xmlStr =mapToXml(xmlData);




        try {
            KeyStore keyStore = null;

            keyStore = KeyStore.getInstance("PKCS12");
            FileInputStream instream = new FileInputStream(new File("G:\\执行中的项目\\金华医药\\cert\\apiclient_cert.p12"));//P12文件目录

            keyStore.load(instream, PropertyUtil.getConfig("wcpay.mchId").toCharArray());

            SSLContext sslcontext = SSLContexts.custom()
                    .loadKeyMaterial(keyStore, PropertyUtil.getConfig("wcpay.mchId").toCharArray())//这里也是写密码的
                    .build();
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
                    sslcontext,
                    new String[]{"TLSv1"},
                    null,
                    SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
            CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();

            HttpPost httpost = new HttpPost("https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers"); // 设置响应头信息
            httpost.addHeader("Connection", "keep-alive");
            httpost.addHeader("Accept", "*/*");
            httpost.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
            httpost.addHeader("Host", "api.mch.weixin.qq.com");
            httpost.addHeader("X-Requested-With", "XMLHttpRequest");
            httpost.addHeader("Cache-Control", "max-age=0");
            httpost.addHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0) ");
            httpost.setEntity(new StringEntity(xmlStr, "UTF-8"));
            CloseableHttpResponse response = httpclient.execute(httpost);

            HttpEntity entity = response.getEntity();

            String jsonStr = EntityUtils.toString(response.getEntity(), "UTF-8");
            System.out.println(jsonStr);
            EntityUtils.consume(entity);

        } catch(Exception e){


        } finally {
         //   httpclient.close();
        }


    }

    /**
     * map转成xml
     * @param arr
     * @return
     */
    public static String mapToXml(Map<String, String> arr) {
        String xml = "<xml>";
        Set<String> keys =   arr.keySet();
        for(String key:keys){
            xml += "<" + key + ">" + arr.get(key) + "</" + key + ">";
        }
        xml += "</xml>";
        return xml;
    }

    /**
     * 对数据签名
     * @param xmlData
     * @param paternerKey
     * @return
     */
    private static String getSign(TreeMap<String, String> xmlData, String paternerKey ) {
        String signStr ="";
        Set<String>  keys = xmlData.keySet();
        for(String key:keys){
            signStr+=key+"="+xmlData.get(key)+"&";
        }
        String stringSignTemp = signStr + "key=" + paternerKey;
        String signValue = DigestUtils.md5Hex(stringSignTemp).toUpperCase();
        return  signValue;
    }

}
